import {dirname,resolve,join} from 'path'
ROOT = join(
  dirname(resolve(__dirname))
  'node_modules'
)

export default {
  name: 'import-node'
  renderChunk:(code,id)=>
    # window 和 mac 的二进制文件导出不一样，必须直接引用.node
    r = code
    for i from code.matchAll /require\('.*\.node'\)/g
      {index} = i
      b = code.lastIndexOf('var ',index)
      pos = code.indexOf('getAugmentedNamespace(',index)
      if pos>0
        e = code.indexOf(')',pos)
        replace_from = code[b..e]
        e = code.lastIndexOf('=',pos)
        b = code.lastIndexOf('var ',e)
        r = r.split(replace_from).join(code[b..e]+i[0])
    code:r

  transform: (code, id) =>
    if not id.endsWith '.node'
      return null
    if id.startsWith(ROOT)
      for i from id[ROOT.length+1..].split('/')
        pos = i.lastIndexOf('@')
        if pos > 0
          i = i[...pos]
          pos = i.lastIndexOf('+')
          if ~pos
            i = i[pos+1..]
          name = i
          break

    code:"export default require('./#{name}.node')"
}
